package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.service.EmployeeService;
import cn.wolfcode.utils.PasswordUtil;
import cn.wolfcode.utils.UserContext;
import cn.wolfcode.vo.JsonResult;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/**
 * 登录|登出处理器
 *
 * @author 杨兴健
 * @Date 2020/7/11 21:45
 */
@Controller
public class LoginController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password) {

        try {
            //从shiro工具中获取主体
            Subject subject = SecurityUtils.getSubject();

            //不用shiro为我们加密
            //String pw = new Md5Hash(password,username,2).toHex();
            //创建token
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            //验证token
            subject.login(token);
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return new JsonResult(false, "账号不存在");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            return new JsonResult(false, "密码错误");
        } catch (Exception e) {
            e.printStackTrace();
            e.printStackTrace();
            return new JsonResult(false, "登录异常，请联系管理员");
        }

        return new JsonResult(true, "登录成功");
    }

    /**
     * 登出
     *
     * @param session
     * @return
     *//*
    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/index.html";
    }*/


}
